package dao

import (
	"context"
	"time"

	"github.com/ego-component/egorm"
	"gorm.io/gorm/clause"
)

// 记录用户读取到群聊的最新消息id
type UserChannelReadRecord struct {
	ID        int   `gorm:"primary_key,autoIncrement"`
	UID       int64 `gorm:"column:uid;uniqueIndex:idx_user_channel,priority:2"`
	ChannelID int64 `gorm:"column:channel_id;uniqueIndex:idx_user_channel,priority:1"`
	LastMsgID int64 `gorm:"column:last_msg_id"`
	Ctime     int64 `gorm:"column:ctime"`
	Utime     int64 `gorm:"column:utime"`
}

func (u UserChannelReadRecord) TableName() string {
	return "user_channel_read_records"
}

type UserChannelReadRecordDAO interface {
	GetLastReadMsgID(ctx context.Context, uid, channelID int64) (int64, error)
	Save(ctx context.Context, record UserChannelReadRecord) error
}

type gormUserChannelReadRecordDAO struct {
	db *egorm.Component
}

func NewGORMUserChannelReadRecordDAO(db *egorm.Component) UserChannelReadRecordDAO {
	return &gormUserChannelReadRecordDAO{
		db: db,
	}
}

func (g *gormUserChannelReadRecordDAO) GetLastReadMsgID(ctx context.Context, uid, channelID int64) (int64, error) {
	var record UserChannelReadRecord
	err := g.db.WithContext(ctx).
		Where("uid = ? AND channel_id = ?", uid, channelID).
		First(&record).Error
	if err != nil {
		return 0, err
	}
	return record.LastMsgID, nil
}

func (g *gormUserChannelReadRecordDAO) Save(ctx context.Context, record UserChannelReadRecord) error {
	nowUnix := time.Now().UnixMilli()
	record.Utime = nowUnix
	record.Ctime = nowUnix

	// 使用 ON DUPLICATE KEY UPDATE 语法
	return g.db.WithContext(ctx).
		Clauses(clause.OnConflict{
			Columns: []clause.Column{
				{Name: "uid"},
				{Name: "channel_id"},
			},
			DoUpdates: clause.Assignments(map[string]interface{}{
				"last_msg_id": record.LastMsgID,
				"utime":       record.Utime,
			}),
		}).
		Create(&record).Error
}
